const { ApiCreater } = require('../../dave/dave.min.js')
let wxPay = (params) => new Promise((resolve, reject) => {
  // Api 设置简直智障 https://developers.weixin.qq.com/miniprogram/dev/api/open-api/payment/wx.requestPayment.html
  let { timeStamp, nonceStr, signType, paySign, packageStr } = params
  wx.requestPayment({
    'timeStamp': timeStamp,
    'nonceStr': nonceStr,
    'package': packageStr,
    'signType': signType,
    'paySign': paySign,
    'success':resolve,
    'fail':reject
  })
})
export default (orderId) => {
    var user =wx.getStorageSync('USER');
  return ApiCreater({
    url: `/web_api/v1/orders/wechat/preOrderByJS?tradeNo=${orderId}&userId=`+user.id,
    method: 'POST'
  })
    .then(response => {
      let transInfo = response.data.result
      let { timeStamp, nonceStr, signType, paySign, packageStr } = transInfo

      return wxPay({ timeStamp, nonceStr, packageStr, signType, paySign })
        .then(
          function (num) {
            console.log("支付成功结果:======>"+num.errMsg)
              wx.redirectTo({url: '/pages/user/order/list/index'})
          },
          function(num){
            //标记是否支付
            wx.setStorageSync('hasPay', false)
            console.log("支付失败结果:======>" + num.errMsg)
              wx.redirectTo({url: '/pages/user/order/list/index'})
          }
          )
    })
}
